﻿// The MIT License (MIT)
// Copyright (c) 2014 Grégory Ghez
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

namespace JenkinsController.Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Framework;
    using Jenkins.Core;
    using Jenkins.Domain;

    internal class DataService : IDataService
    {
        private readonly CollectionHelper collectionHelper;
        private readonly IJenkinsRestClient restClient;

        public DataService(CollectionHelper collectionHelper, IJenkinsRestClient restClient)
        {
            if (collectionHelper == null)
            {
                throw new ArgumentNullException("collectionHelper");
            }

            if (restClient == null)
            {
                throw new ArgumentNullException("restClient");
            }

            this.collectionHelper = collectionHelper;
            this.restClient = restClient;
        }

        public IJenkinsRestClient RestClient
        {
            get { return this.restClient; }
        }

        public async Task UpdateAsync(JenkinsServer server)
        {
            this.OnStartLoading();
            JenkinsServer update;
            if (server == null || (update = await this.restClient.GetServerAsync(server.Url, false)) == null || update.Node == null)
            {
                return;
            }

            if (server.Node == null)
            {
                server.Node = update.Node;
            }
            else
            {
                server.Node.Description = update.Node.Description;
                server.Node.IsQuietingDown = update.Node.IsQuietingDown;
                server.Node.Mode = update.Node.Mode;
                server.Node.NodeDescription = update.Node.NodeDescription;
                server.Node.NodeName = update.Node.NodeName;
                server.Node.NumExecutors = update.Node.NumExecutors;
                server.Node.UseSecurity = update.Node.UseSecurity;
                server.Node.UseCrumbs = update.Node.UseCrumbs;
                server.Node.SlaveAgentPort = update.Node.SlaveAgentPort;
            }

            if (!this.collectionHelper.AreSynchronized(update.Node.Jobs, server.Node.Jobs, j => j.Url))
            {
                server.Node.Jobs = update.Node.Jobs;
            }

            if (!this.collectionHelper.AreSynchronized(update.Node.Views, server.Node.Views, j => j.Url))
            {
                server.Node.Views = update.Node.Views;
            }

            if (update.Node.PrimaryView == null || server.Node.PrimaryView == null || !string.Equals(update.Node.PrimaryView.Url, server.Node.PrimaryView.Url, StringComparison.OrdinalIgnoreCase))
            {
                server.Node.PrimaryView = update.Node.PrimaryView;
            }

            if (update.Users == null || server.Users == null || !this.collectionHelper.AreSynchronized(update.Users, server.Users, u => u.FullName))
            {
                server.Users = update.Users;
            }
            this.OnEndLoading();
        }

        public async Task UpdateAsync(JenkinsBuild build)
        {
            this.OnStartLoading();
            JenkinsBuild update;
            if (build == null || (update = await this.restClient.GetBuildAsync(build.RestUrl, true)) == null)
            {
                return;
            }

            if (!this.collectionHelper.AreSynchronized(build.Artifacts, update.Artifacts, a => a.FileName))
            {
                build.Artifacts = update.Artifacts;
            }

            build.TestReport = update.TestReport;
            build.ChangeSet = update.ChangeSet;
            build.DisplayName = update.DisplayName;
            build.Duration = update.Duration;
            build.EstimatedDuration = update.EstimatedDuration;
            build.Id = update.Id;
            build.IsBuilding = update.IsBuilding;
            build.Number = update.Number;
            build.Status = update.Status;
            build.TimeStamp = update.TimeStamp;

            this.OnEndLoading();
        }

        public async Task UpdateAsync(JenkinsJob job)
        {
            this.OnStartLoading();
            JenkinsJob update;
            if (job == null || (update = await this.restClient.GetJobAsync(job.RestUrl, false)) == null)
            {
                return;
            }

            job.Buildable = update.Buildable;
            job.Description = update.Description;
            job.DisplayName = update.DisplayName;
            job.IsInQueue = update.IsInQueue;
            job.Name = update.Name;
            job.NextBuildNumber = update.NextBuildNumber;
            job.Status = update.Status;

            if (!this.collectionHelper.AreSynchronized(job.Builds, update.Builds, b => b.Url))
            {
                if (job.Builds == null)
                {
                    job.Builds = update.Builds;
                }
                else
                {
                    var builds = job.Builds.ToList();
                    // Remove no more existing builds
                    builds.RemoveAll(b => !update.Builds.Any(ub => string.Equals(ub.Url, b.Url, StringComparison.OrdinalIgnoreCase)));

                    // Insert new builds
                    var newBuilds = update.Builds.Where(ub => !builds.Any(b => string.Equals(b.Url, ub.Url, StringComparison.OrdinalIgnoreCase))).ToList();
                    foreach (var build in newBuilds)
                    {
                        var index = Math.Max(0, builds.FindIndex(0, b => b.Number < build.Number));
                        builds.Insert(index, build);
                    }

                    job.Builds = builds.ToArray();
                }
            }

            if (update.LastBuild != null)
            {
                job.LastBuild = await this.restClient.GetBuildAsync(update.LastBuild.RestUrl, false);
            }

            if (update.LastCompletedBuild != null)
            {
                job.LastCompletedBuild = await this.restClient.GetBuildAsync(update.LastCompletedBuild.RestUrl, false);
            }

            if (update.LastFailedBuild != null)
            {
                job.LastFailedBuild = await this.restClient.GetBuildAsync(update.LastFailedBuild.RestUrl, false);
            }

            job.LastStableBuild = update.LastStableBuild;
            job.LastSuccessfulBuild = update.LastSuccessfulBuild;
            job.LastUnstableBuild = update.LastUnstableBuild;
            job.LastUnsuccessfulBuild = update.LastUnsuccessfulBuild;

            this.OnEndLoading();
        }

        public async Task RunJobAsync(JenkinsJob job)
        {
            this.OnStartLoading();
            if (job != null)
            {
                JenkinsJobStatus status = job.Status;

                await this.restClient.RunJobAsync(job);

                // Try get updated status of job quickly
                for (int i = 0; i < 4; i++)
                {
                    await Task.Delay(TimeSpan.FromSeconds(3d)).ContinueWith(ant => this.UpdateAsync(job));

                    // Break quick update loop if status changed
                    if (!Equals(status, job.Status))
                    {
                        break;
                    }
                }
            }
            this.OnEndLoading();
        }

        public async Task StopJobAsync(JenkinsJob job)
        {
            this.OnStartLoading();
            JenkinsJob update;
            if (job == null || (update = await this.restClient.GetJobAsync(job.RestUrl, false)) == null)
            {
                return;
            }

            JenkinsJobStatus status = job.Status;

            await this.restClient.StopJobAsync(update);

            // Try get updated status of job quickly
            for (int i = 0; i < 4; i++)
            {
                await Task.Delay(TimeSpan.FromSeconds(3d)).ContinueWith(ant => this.UpdateAsync(job));

                // Break quick update loop if status changed
                if (!Equals(status, job.Status))
                {
                    break;
                }
            }
            this.OnEndLoading();
        }

        public event EventHandler StartLoading;
        public event EventHandler EndLoading;

        public async Task UpdateAsync(JenkinsView view)
        {
            this.OnStartLoading();
            JenkinsView update;
            if (view == null || (update = await this.restClient.GetViewAsync(view.DetailsUrl, false)) == null)
            {
                return;
            }

            view.Description = update.Description;

            if (!this.collectionHelper.AreSynchronized(update.Jobs, view.Jobs, j => j.Url))
            {
                view.Jobs = update.Jobs;
            }

            this.OnEndLoading();
        }

        private void OnStartLoading()
        {
            EventHandler handler = this.StartLoading;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        private void OnEndLoading()
        {
            EventHandler handler = this.EndLoading;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }
}